package com.qiantu.phone.ui.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.LinkageNewBean;
import com.qiantu.api.entity.MemberBean;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.api.entity.SubMessagePeople;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.adapter.PushReceiverAdapter;
import com.qiantu.phone.ui.dialog.BottomCheckListDialog;
import com.qiantu.phone.utils.LinkageDataHolder;
import com.qiantu.phone.utils.TempDataHolder;
import com.lxj.xpopup.XPopup;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class PushMessageSettingActivityNew extends AppActivity {

    private EditText editPushContent;
    private SettingBar settingReceiver;
    private String serialNo;
    private List<MemberBean> members;
    private LinkageNewBean mLinkageBean;
    private SceneDetailBean mSceneDetailBean;
    private LinkageBean.LinkageTask mLinkageTask;
    private SceneDetailBean.ScenePushMessage mScenePushMessage;
    private SceneDetailBean.SceneTaskBean mSceneTask;
    private String message;
    private List<SubMessagePeople> mSubMessagePeople;
    private int sceneType;
    private int mPosition;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_push_message_setting;
    }

    @Override
    protected void initView() {
        sceneType = getInt("sceneType", 1);
        mPosition = getInt("position", -1);
        editPushContent = findViewById(R.id.edit_push_content);
        settingReceiver = findViewById(R.id.setting_receiver);
        editPushContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                canSubmit();
            }
        });
        setOnClickListener(settingReceiver);
    }

    @Override
    protected void initData() {
        getMembers();
        serialNo = getString("serial_no");
        mLinkageBean = LinkageDataHolder.getLinkageDataNew();
        if (mLinkageBean != null) {
            List<LinkageBean.LinkageTask> linkageTasks = mLinkageBean.getLinkageTasks();
            if (linkageTasks != null && linkageTasks.size() > 0 && !TextUtils.isEmpty(serialNo)) {
                for (LinkageBean.LinkageTask item : linkageTasks) {
                    if (!TextUtils.isEmpty(item.getTaskSerialNo()) && item.getTaskSerialNo().equals(serialNo)) {
                        mLinkageTask = item;
                        mSubMessagePeople = mLinkageTask.getSubMessagePeople();
                        message = mLinkageTask.getMessage();
                        break;
                    }
                }
            }
        }
        editPushContent.setText(message);
    }

    private void updateReceiver() {
        if (mSubMessagePeople != null) {
            if(mSubMessagePeople.size() == 1){
                for(MemberBean memberBean : members){
                    if(memberBean.getUserSerialNo().equals(mSubMessagePeople.get(0).getUserSerialNo())){
                        settingReceiver.setRightText(memberBean.getMemberNickName());
                    }
                }
            }else{
                settingReceiver.setRightText(getString(R.string.how_many_people, mSubMessagePeople.size()));
            }
        }else{
            if (mSubMessagePeople == null) {
                mSubMessagePeople = new ArrayList<>();
            } else {
                mSubMessagePeople.clear();
            }
            MemberBean member = members.get(0);
            SubMessagePeople subMessagePeople = new SubMessagePeople();
            subMessagePeople.setUserName(member.getUserNickName());
            subMessagePeople.setUserSerialNo(member.getUserSerialNo());
            subMessagePeople.setSubMessageType("0");
            mSubMessagePeople.add(subMessagePeople);
            settingReceiver.setRightText(member.getMemberNickName());
        }
    }

    @Override
    public void onRightClick(View view) {
        message = editPushContent.getText() == null ? null : editPushContent.getText().toString().trim();
        if (TextUtils.isEmpty(message)) {
            toast(R.string.push_content_hint);
            return;
        }
        if (mSubMessagePeople == null || mSubMessagePeople.size() == 0) {
            toast(R.string.select_receiver);
            return;
        }
                //当前联动空，才去
                if (mLinkageTask == null) {
                    //本地保存联动条件
                    if (mLinkageBean == null) {
                        mLinkageBean = new LinkageNewBean();
                        LinkageDataHolder.setLinkageDataNew(mLinkageBean);
                    }
                    List<LinkageBean.LinkageTask> linkageTasks = mLinkageBean.getLinkageTasks();
                    if (linkageTasks == null) {
                        linkageTasks = new ArrayList<>();
                    }
                    mLinkageBean.setLinkageTasks(linkageTasks);
                    mLinkageTask = new LinkageBean.LinkageTask();
                    //先设置个本地的SerialNo，为了编辑找到对应的数据
                    mLinkageTask.setTaskSerialNo(UUID.randomUUID().toString());
                    mLinkageTask.setTaskType(3);
                    if(mPosition < 0){
                        linkageTasks.add(mLinkageTask);
                    }else{
                        linkageTasks.add(mPosition, mLinkageTask);
                    }
                    mLinkageTask.setSort(linkageTasks.indexOf(mLinkageTask) + 1);
                }
                mLinkageTask.setTitle("");
                mLinkageTask.setMessage(message);
                mLinkageTask.setSubMessagePeople(mSubMessagePeople);
                mLinkageTask.setImageUrl("icon_intelligent_action_push");
                mLinkageTask.setBriefing("推送消息");
                startActivity_SingleTask(EditLinkageActivityNew.class);
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setting_receiver:
                if (members == null) {
                    getMembers();
                } else {
                    showBottomCheckListDialog();
                }
                break;
        }
    }

    private void canSubmit() {
        getTitleBar().getRightView().setEnabled(editPushContent.getText().length() > 0 && mSubMessagePeople != null && mSubMessagePeople.size() > 0);
    }

    private BottomCheckListDialog mBottomCheckListDialog;

    private void showBottomCheckListDialog() {
        if (mBottomCheckListDialog == null) {
            mBottomCheckListDialog = new BottomCheckListDialog(this);
            mBottomCheckListDialog.setLabel(getString(R.string.select_receiver));
            mBottomCheckListDialog.setDialogClickListener(new BottomCheckListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    PushReceiverAdapter adapter = (PushReceiverAdapter) mBottomCheckListDialog.getAdapter();
                    Map<String, MemberBean> selected = adapter.getSelected();
                    if (mSubMessagePeople == null) {
                        mSubMessagePeople = new ArrayList<>();
                    } else {
                        mSubMessagePeople.clear();
                    }
                    if (selected != null && selected.size() > 0) {
                        for (String key : selected.keySet()) {
                            MemberBean member = selected.get(key);
                            SubMessagePeople subMessagePeople = new SubMessagePeople();
                            subMessagePeople.setUserName(member.getUserNickName());
                            subMessagePeople.setUserSerialNo(member.getUserSerialNo());
                            subMessagePeople.setSubMessageType("0");
                            mSubMessagePeople.add(subMessagePeople);
                        }
                        if(selected.size() == 1){
                            for(String key : selected.keySet()){
                                MemberBean member = selected.get(key);
                                settingReceiver.setRightText(member.getMemberNickName());
                                break;
                            }
                        }else{
                            settingReceiver.setRightText(getString(R.string.how_many_people, selected.size()));
                        }
//                        if(selected.size() > 1){
//                            settingReceiver.setRightText(getString(R.string.how_many_people, selected.size()));
//                        }else{
//                            settingReceiver.setRightText(null);
//                        }
                    } else {
                        settingReceiver.setRightText(null);
                        toast(R.string.select_receiver);
                    }
                    canSubmit();
                    mBottomCheckListDialog.dismiss();
                }
            });
            PushReceiverAdapter pushReceiverAdapter = new PushReceiverAdapter(this);
            mBottomCheckListDialog.setAdapter(pushReceiverAdapter);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomCheckListDialog);
        }
        PushReceiverAdapter pushReceiverAdapter = (PushReceiverAdapter) mBottomCheckListDialog.getAdapter();
        pushReceiverAdapter.setData(members);
        pushReceiverAdapter.checked(members.get(0).getUserSerialNo());
        if (mSubMessagePeople != null && mSubMessagePeople.size() > 0) {
            List<String> checked = new ArrayList<>();
            for (SubMessagePeople subMessagePeople : mSubMessagePeople) {
                checked.add(subMessagePeople.getUserSerialNo());
            }
            pushReceiverAdapter.checked(checked);
        }
        mBottomCheckListDialog.show();
    }

    private void getMembers() {
        LLHttpManager.getHouseMembers(this, AppApplication.getInstance().getCurrentHouseSerialNo(), new HttpCallback<HttpData<List<MemberBean>>>(null) {
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<List<MemberBean>> result) {
                members = result.getData();
                if(members != null){
                    for(int i=0; i<members.size(); i++){
                        MemberBean memberBean = members.get(i);
                        if(memberBean.getUserPhone().equals(AppApplication.getInstance().getLoginInfo().getUserInfo().getPhone())){
                            memberBean.setMemberNickName(getString(R.string.oneself));
                            members.add(0, members.remove(i));
                            break;
                        }
                    }
                    updateReceiver();
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }
}